package com.demo.config.redis;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration
public class RedisConfig {

    /**
     * 配置 RedisCacheManager，使用 cache 注解管理 redis 缓存
     */
    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 初始化一个RedisCacheWriter
        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        final JavaType javaType = TypeFactory.defaultInstance().constructType(Object.class);
        RedisCacheConfiguration defaultCacheConfig = CacheManagerConfig.getConfig(javaType);

        return new MyRedisCacheManager(cacheWriter, defaultCacheConfig);
    }
}
